import React, { PureComponent } from 'react'
import { Button, DatePicker, Form, Input, message, Radio, Select } from 'antd'
import moment from 'moment'
import { regExp } from '@/utils/regExp'
import styles from './index.less'
import { dataqualityFields, dataqualityTables, getRuleTemplates, saveRule } from '../api'

const { Option } = Select

class DataQualityCreate extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      tables: [],
    }
    this.form = React.createRef()
  }

  componentDidMount() {
    this.dataqualityTables()

    this.set(this.props.data)
  }

  set = (data) => {
    if (!data) return
    if (data.ruleType || data.ruleType === 0) { this.getRuleTemplates(data) }
    this.dataqualityFields(data.tblName)
    data.ruleConditions && data.ruleCondition
      ? data.ruleConditions.map((obj) => {
        obj.items
          && obj.items.map((o, k) => {
            o.value = JSON.parse(data.ruleCondition)[k].value
          })
      })
      : null
    this.setState(
      {
        tblId: data.tblId,
        dataReplaceRuleId: data.ruleDiy,
        max: data.max,
        min: data.min,
        templateId: data.templateId,
        // hasPartition: data.ruleDiy,
        fieldTypes: data.fieldTypes,
        compareTypes: data.compareTypes,
        expectValue: data.expectValue,
        ruleTemplatesItem: data.ruleConditions
          ? { ruleConditions: data.ruleConditions }
          : null,
      },
      () => {
        const val = {
          tblName: data.tblName,
          ruleName: data.ruleName,
          remark: data.remark,
          new: data.max || data.min || 0,
          // ruleStrength: data.ruleStrength,
          partitionExpression: data.partitionExpression,
          templateFilter: data.templateFilter,
          diySql: data.diySql,
          ruleType: data.ruleType,
          templateId: data.templateId,
          fieldNames: data.ruleDiy == 0 ? data.fieldNames && data.fieldNames.split(',') : data.fieldNames,
          ruleCompareType: data.ruleDiy == 0 ? data.ruleCompareType && data.ruleCompareType.split(',') : data.ruleCompareType,
          ruleExpectValue: data.ruleExpectValue,
          ruleDiy: data.ruleDiy,
        }
        data.ruleCondition
          && JSON.parse(data.ruleCondition).map((obj) => {
            if (obj.key === 'date') {
              val[obj.key] = moment(obj.value, 'YYYY-MM-DD')
            } else {
              val[obj.key] = obj.value
            }
          })
        this.form && this.form.current.setFieldsValue({
          ...val,
        })
      },
    )
  }

  dataqualityTables = () => {
    dataqualityTables().then((res) => {
      if (res.status === 200) {
        this.setState({
          tables: res.data,
        })
      }
    })
  }

  dataqualityFields = (tableName) => {
    dataqualityFields({ tableName }).then((res) => {
      if (res.status === 200) {
        this.setState({
          fields: res.data,
        })
        const hasPartition = (res.data || []).filter((item) => item.partition).length > 0
        this.setState({
          fields: res.data,
          hasPartition,
        })
      } else {
        this.setState({
          fields: [],
          hasPartition: false,
        })
      }
    })
  }

  getRuleTemplates = (data) => {
    getRuleTemplates({
      templateTableType: data.ruleType,
    }).then((res) => {
      if (res.status === 200) {
        this.setState({
          ruleTemplates: res.data,
        })
      } else {
        this.setState({
          ruleTemplates: [],
        })
      }
    })
  }

  /**
   * 构建sql
   */
  // sql = () => {
  //   const { hasPartition } = this.state
  //   const values = this.form.current.getFieldsValue()
  //   const tableName = values.tblName
  //   if (values.ruleDiyStatisticalModel && values.fieldNames && tableName) {
  //     const arr = []
  //     values.fieldNames.map((val) => {
  //       arr.push(
  //         `select ${values.ruleDiyStatisticalModel}(${val}) from ${tableName
  //         } ${hasPartition == 0 || values.partitionExpression === undefined
  //           ? ''
  //           : `where ${values.partitionExpression}\n`
  //         }`,
  //       )
  //     })
  //     this.setState({
  //       sql: arr.join(),
  //     })
  //   }
  // };

  valuesChange = (value, allValues) => {
    const key = Object.keys(value)[0]
    if (key === 'tblName') {
      this.dataqualityFields(allValues.tblName)
      this.setState({
        isMdTable: /^md_/.test(allValues.tblName),
      })
    }
    if (allValues.ruleType || allValues.ruleType === 0) { this.getRuleTemplates(allValues) }
    if (key === 'ruleDiy') {
      this.setState({
        dataReplaceRuleId: allValues.ruleDiy,
      })
    }
  }

  /**
   * 获取内置模板的规则
   */
  modelRule = () => {
    const { setFieldsValue } = this.form.current

    const {
      ruleTemplatesItem, compareTypes, expectValue, ruleTemplates, isMdTable, templateId,
    } = this.state
    const r = '^[0-9,\,]*$'
    return (
      <div>
        <Form.Item
          label="规则类型"
          name="ruleType"
          rules={[{ required: true, message: '规则类型不能为空' }]}
        >
          <Select
            onChange={(value) => {
              setFieldsValue({
                templateId: undefined,
              })
              this.setState(
                {
                  ruleTemplatesItem: null,
                  compareTypes: null,
                  expectValue: null,
                },
              )
            }}
            placeholder="请选择规则类型"
          >
            <Option value={0}>字段级规则</Option>
            {/* <Option value={1}>表级规则</Option> */}
          </Select>
        </Form.Item>

        <Form.Item
          label="规则模板"
          name="templateId"
          rules={[{ required: true, message: '规则模板不能为空' }]}
        >
          <Select
            placeholder="请选择规则模板"
            onChange={(value, e) => {
              this.form && this.form.current.setFieldsValue({
                ruleCompareType: undefined,
              })
              this.setState(
                {
                  ruleTemplatesItem: e.item,
                  compareTypes: e.item.compareTypes,
                  expectValue: e.item.expectValue,
                  templateId: e.item.id,
                },
              )
            }}
          >
            {ruleTemplates
              && ruleTemplates.map((obj, k) => (
                <Option
                  key={k}
                  item={obj}
                  value={obj.id}
                >
                  {obj.name}
                </Option>
              ))}
          </Select>
        </Form.Item>
        <Form.Item
          label="过滤条件"
          name="templateFilter"
        >
          <Input.TextArea placeholder="请输入过滤条件" />
        </Form.Item>

        {compareTypes && (
          <Form.Item
            label="比较方式"
            name="ruleCompareType"
            style={{ clear: 'both' }}
            rules={[
              {
                required: true,
                message: '比较方式不能为空',
              },
            ]}
          >
            <Select
              mode={templateId == 9 || templateId == 4 ? 'multiple' : null}
              showSearch
              optionFilterProp="children"
              filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
              placeholder="请选择比较方式">
              {compareTypes.map((obj, key) => (
                <Option key={key} value={String(obj.compareType)}>
                  {obj.desc}
                </Option>
              ))}
            </Select>
          </Form.Item>
        )}
        {ruleTemplatesItem
          && ruleTemplatesItem.ruleConditions
          && ruleTemplatesItem.ruleConditions.length
          && ruleTemplatesItem.ruleConditions[0].items.length > 1
          ? (
            <Form.Item
              label={ruleTemplatesItem.ruleConditions[0].name}
              name="new"
              rules={[
                {
                  required: true,
                  message: `${ruleTemplatesItem.ruleConditions[0].name}不能为空`,
                },
              ]}
            >
              <div className="site-input-group-wrapper">
                <Input.Group compact>
                  <Input
                    style={{ width: '1.5rem' }}
                    placeholder="最小值"
                    type="number"
                    min={0}
                    value={ruleTemplatesItem.ruleConditions[0].items[0].value}
                    onChange={(e) => {
                      ruleTemplatesItem.ruleConditions[0].items[0].value = e.target.value
                      this.setState({
                        min: e.target.value,
                      })
                    }}
                  />
                  <Input
                    className="site-input-split"
                    style={{
                      width: 30,
                      borderLeft: 0,
                      borderRight: 0,
                      pointerEvents: 'none',
                    }}
                    placeholder="~"
                    disabled
                  />
                  <Input
                    className="site-input-right"
                    style={{
                      width: '1.5rem',
                    }}
                    min={0}
                    type="number"
                    value={ruleTemplatesItem.ruleConditions[0].items[1].value}
                    placeholder="最大值"
                    onChange={(e) => {
                      ruleTemplatesItem.ruleConditions[0].items[1].value = e.target.value
                      this.setState({
                        max: e.target.value,
                      })
                    }}
                  />
                </Input.Group>
              </div>
            </Form.Item>
          )
          : ruleTemplatesItem
          && ruleTemplatesItem.ruleConditions
          && ruleTemplatesItem.ruleConditions[0]
          && ruleTemplatesItem.ruleConditions[0].items
          && ruleTemplatesItem.ruleConditions[0].items.map(
            (obj, k) => (
              <div key={k}>
                <Form.Item
                  label={ruleTemplatesItem.ruleConditions[0].name}
                  name={obj.key}
                  rules={[
                    {
                      required: true,
                      message: `${ruleTemplatesItem.ruleConditions[0].name}不能为空`,
                    },
                    {
                      required: false,
                      pattern: obj.dataType == 'number' ? new RegExp(r) : null,
                      message: '只支持数字和逗号',
                    },
                  ]}
                >
                  {{
                    number: <Input
                      placeholder={obj.placeholder}
                      onChange={(e) => {
                        obj.value = e.target.value
                      }}
                    />,
                    text: <Input
                      onChange={(e) => {
                        obj.value = e.target.value
                      }}
                      placeholder={obj.placeholder}
                    />,
                    date: <DatePicker
                      onChange={(_date, dateString) => {
                        obj.value = dateString
                      }}
                      placeholder={obj.placeholder}
                    />,
                  }[obj.dataType]}
                </Form.Item>
              </div>
            ),
          )}
        {expectValue && (
          <Form.Item
            label="期望值"
            name="ruleExpectValue"
            rules={[
              {
                required: true,
                message: '期望值不能为空',
              },
            ]}
          ><Input placeholder="请输入期望值" type="number" />
          </Form.Item>
        )}
      </div>
    )
  };

  /**
   * 获取自定义模板的规则
   */
  customRule = () => {
    return (
      <div>
        <Form.Item label="SQL" name="diySql">
          <Input.TextArea
            placeholder="请输入SQL"
            autoSize={{ minRows: 3, maxRows: 5 }}
          />
        </Form.Item>
        <Form.Item
          label="比较方式"
          name="ruleCompareType"
          rules={[
            {
              required: true,
              message: '比较方式不能为空',
            },
          ]}
        >
          <Select placeholder="请选择比较方式">
            <Option value="0">大于</Option>
            <Option value="1">大于等于</Option>
            <Option value="2">等于</Option>
            <Option value="3">小于</Option>
            <Option value="4">小于等于</Option>
            <Option value="5">不等于</Option>
            <Option value="6">属于</Option>
            <Option value="7">不属于</Option>
          </Select>
        </Form.Item>
        <Form.Item
          label="期望值"
          name="ruleExpectValue"
          rules={[
            {
              required: true,
              message: '期望值不能为空',
            },
          ]}
        ><Input placeholder="请输入期望值" type="number" />
        </Form.Item>
      </div>
    )
  };

  onFinish = (values) => {
    const { taskNode } = this.props
    const {
      fieldTypes, tblId, max, min, ruleTemplatesItem, dataReplaceRuleId
    } = this.state

    saveRule({
      ...values,
      fieldTypes,
      tblId,
      nodeId: taskNode.id,
      fieldNames: Array.isArray(values.fieldNames) ? values.fieldNames?.join(',') : values.fieldNames,
      ruleCompareType: Array.isArray(values.ruleCompareType) ? values.ruleCompareType?.join(',') : values.ruleCompareType,
      max,
      min,
      ruleCondition:
        ruleTemplatesItem
          && ruleTemplatesItem.ruleConditions
          && ruleTemplatesItem.ruleConditions[0]
          ? JSON.stringify(ruleTemplatesItem.ruleConditions[0].items)
          : null,
    }).then((res) => {
      if (res.status === 200) {
        message.success(res.msg)
        this.props.dataqualityDetail()
      } else {
        message.error(res.msg)
      }
    })
  }

  render() {
    const {
      tables, fields, dataReplaceRuleId, hasPartition,
    } = this.state
    return (
      <div className={styles.data_quality_create}>
        <Form
          className={styles.form}
          colon={false}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          onFinish={this.onFinish}
          onValuesChange={this.valuesChange}
          ref={this.form}
        >
          <Form.Item
            label="数据表"
            name="tblName"
            rules={[{ required: true, message: '请选择数据表' }]}
          >
            <Select
              showSearch
              filterOption={(input, option) => option.title.toLowerCase().indexOf(input.toLowerCase()) >= 0}
              allowClear
              placeholder="请选择数据目标"
              onChange={(value, e) => {
                this.setState({
                  tblId: e.key,
                })
              }}

            >
              {tables && tables.map((item) => <Option title={item.tableName} value={item.tableName} key={item.tblId}>{item.tableName}</Option>)}
            </Select>
          </Form.Item>
          {dataReplaceRuleId == 0 ? (
            <Form.Item
              label="规则字段"
              name="fieldNames"
              optionFilterProp="children"
              rules={[{ required: true, message: '请选择规则字段' }]}
            >

              <Select
                mode="multiple"
                placeholder="请选择规则字段"
                showSearch
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                onChange={(value, e) => {
                  const arr = []
                  e.map((o) => {
                    arr.push(o.props.type)
                  })
                  this.setState(
                    {
                      fieldTypes: arr && arr.join(','),
                    }
                  )
                }}
              >
                {fields && fields.map((item, i) => (
                  <Option
                    key={i}
                    type={item.fieldType}
                    value={item.fieldName}
                  >{item.fieldName}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          ) : null}
          {hasPartition ? (
            <Form.Item
              label="分区表达式"
              name="partitionExpression"
              rules={[
                {
                  required: true,
                  message: '分区表达式不能为空',
                },
              ]}
            >
              <Input
                placeholder="请输入分区表达式"
                autoComplete="off"
                onChange={() => {
                  this.setState({}, () => {
                    this.sql()
                  })
                }}
                min={0}
              />
            </Form.Item>
          ) : null}
          {/* <Form.Item
            label="强弱"
            name="ruleStrength"
            rules={[{ required: true, message: '请选择强弱' }]}
          >
            <Radio.Group>
              <Radio value={0}>强</Radio>
              <Radio value={1}>弱</Radio>
            </Radio.Group>
          </Form.Item> */}
          <Form.Item
            label="规则"
            name="ruleDiy"
            rules={[{ required: true, message: '请选择规则' }]}
          >
            <Radio.Group>
              <Radio value={0}>模板规则</Radio>
              <Radio value={1}>自定义规则</Radio>
            </Radio.Group>
          </Form.Item>
          {(dataReplaceRuleId || dataReplaceRuleId === 0) && {
            0: this.modelRule(),
            1: this.customRule(),
          }[dataReplaceRuleId]}
          <Form.Item
            label="描述"
            name="remark"
            rules={[
              {
                required: false,
                pattern: new RegExp(regExp.proName(0, 128).reg, 'g'),
                message: regExp.proName(0, 128).text,
              },
            ]}
          >
            <Input.TextArea placeholder="请输入规则描述" />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Form.Item>
        </Form>
      </div>
    )
  }
}

export default DataQualityCreate
